package com.xinqi.modules.user.users.third.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.modules.user.third.dto.rsp.UserLoginLogResultDTO;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.modules.user.users.third.convert.UserLoginLogConvert;
import com.xinqi.modules.user.users.third.domain.UserLoginLogEntity;
import com.xinqi.modules.user.users.third.manager.UserLoginLogManager;
import com.xinqi.modules.user.users.third.service.UserLoginLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 设备表服务层实现
 *
 * @author: yyzhen
 * @date: 2023/07/17
 */
@Validated
@Service("userLoginLogService")
@RequiredArgsConstructor
public class UserLoginLogServiceImpl implements UserLoginLogService {
    private final UserLoginLogConvert userLoginLogConvert;
    private final UserLoginLogManager userLoginLogManager;

    /**
     * 根据id查询 设备表数据
     */
    @Override
    @DS("slaver")
    public UserLoginLogResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), MessageUtils.message("sys.user.id.not.blank"));
        return Optional.ofNullable(this.userLoginLogManager.getById(id)).map(userLoginLogConvert::convert).orElse(null);
    }

    /**
     * 根据id删除 设备表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), MessageUtils.message("sys.user.id.not.blank"));
        return this.userLoginLogManager.deleteById(id);
    }

    /**
     * 查询用户设备列表
     *
     * @param userId
     * @return
     */
    @Override
    @DS("slaver")
    public List<UserLoginLogResultDTO> findByUserId(Long userId) {
        LambdaQueryWrapper<UserLoginLogEntity> wrapper = new LambdaQueryWrapper<UserLoginLogEntity>()
            .eq(UserLoginLogEntity::getUserId, userId)
            .orderByDesc(UserLoginLogEntity::getLastLogin);
        return userLoginLogManager.list(wrapper).stream()
            .map(userLoginLogConvert::convert).collect(Collectors.toList());
    }

}
